from PIL import Image
from PIL import ImageGrab


def water_drop_cutting(img:Image.Image):
    '''
    水滴法切割出大致模块
    :param img:
    :return:
    '''
    w,h=img.size
    pix=img.load()

    horizontal=[]#水平方向
    x=0
    while x<w:
        flag = any([True for y in range(h) if pix[x, y][0] + pix[x, y][1] + pix[x, y][2] < 300])
        if flag:
            for xv in range(x+1,w):
                flag = any([True for y in range(h) if pix[xv, y][0] + pix[xv, y][1] + pix[xv, y][2] < 300])
                if not flag:
                    break
            horizontal.append((x,xv))
            x = xv
        x+=1

    vertical = []# 垂直方向
    y=0
    while y<h:
        flag=any([True for x in range(w) if pix[x,y][0]+pix[x,y][1]+pix[x,y][2]<300])
        if flag:
            for yv in range(y+1,h):
                flag = any([True for x in range(w) if pix[x, yv][0] + pix[x, yv][1] + pix[x, yv][2] < 300])
                if not flag:
                    break
            vertical.append((y,yv))
            y=yv
        y+=1

    return horizontal,vertical

def binarization(img:Image.Image):
    '''
    二值化图片
    :param img:
    :return:
    '''
    w,h=img.size
    hold=110
    pix = img.load()
    for x in range(w):
        for y in range(h):
            r, g, b =pix[x, y]
            if r > hold and g > hold and b > hold:
                pix[x, y] =(0, 0, 0)
            else:
                pix[x, y] =  (255, 255, 255)
    return img


def getShotPic():
    img = ImageGrab.grab(bbox=(0, 0, 1700,800))
    return img

def checkFinish(img=None):
    if img ==None:
        img=getShotPic()
    img=img.crop((1213,402,1266,425))
    horizontal, vertical= water_drop_cutting(binarization(img))
    print(horizontal,vertical) #[(19, 25), (27, 33), (35, 46)] [(8, 18)]
    if len(horizontal)==3 and len(vertical)==1 and horizontal[0][0]<10:
        print("当前再转录")
    else:
        print("不在转录")
    return len(horizontal)==3 and len(vertical)==1 and horizontal[0][0]<10

if __name__=="__main__":
    img=Image.open(r"C:\Users\Administrator\Documents\Sunlogin Files\sunlogin_20210827141805.bmp")
    print(checkFinish(img))
    #getShotPic().save("4564654.png")

